package com.pxxy.mall.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pxxy.common.to.es.SkuEsModel;
import com.pxxy.mall.search.config.MallElasticSearchConfig;
import com.pxxy.mall.search.constant.EsConstant;
import com.pxxy.mall.search.service.ProductSaveService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.action.cat.RestHealthAction;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author zhangjj
 * @since 2024/1/12
 */
@Slf4j
@Service
@AllArgsConstructor
public class ProductSaveServiceImpl implements ProductSaveService {

    private RestHighLevelClient client;

    @Override
    public boolean productSave(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSONObject.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = client.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        if (!b) {
            List<String> collect = Arrays.stream(bulk.getItems()).map(t -> t.getId()).collect(Collectors.toList());
            log.info("商品上架完成：{}", collect);
        }
        return b;
    }
}
